#############################################################################
#
# Just Another Package Builder http://code.google.com/p/japb
# (c)2011 Alexander Galanin
#
# Functions for RPM packages generation
#
# $Id$
#
#############################################################################

package require Tcl 8.5
package require japb::filenode
package require japb::tcl

package provide japb::rpm 1.0

namespace eval japb {

namespace export rpm

namespace eval rpm {

namespace import ::japb::filenode

# Create and RPM package
# @param name package name
# @param version package version
# @param arch package architecture
# @param specHeader file with .spec file header
# @param args file nodes to put into archive in format:
#        node owner:group permissions
proc rpm {name version arch specHeader args} {
    set rpmBuildDir [filenode mkdir rpm-$name-$version-$arch-build]
    set rpmOutputDir [filenode mkdir rpm-$name-$version-$arch-output]
    set spec [filenode mkfile rpm.spec]

    set arch [rpmArchitecture $arch]
    set rpmname "$name-$version-1.$arch.rpm"

    # read rpm header
    set f [open $specHeader r]
    set header [read $f]
    close $f

    # fill spec file
    set f [open [filenode path $spec] w]
    puts $f "%define version $version"
    puts $f "%define name $name"
    puts $f "%define _rpmdir [filenode path $rpmOutputDir]"
    puts $f $header
    puts $f "%files"
    foreach {fd owner perm} $args {
        set owner [split $owner :]
        set attr "%attr($perm,[lindex $owner 0],[lindex $owner 1])"
        puts $f "$attr [filenode name $fd]"
        filenode copyToDir $fd $rpmBuildDir
    }
    close $f

    # executing rpmbuild
    exec rpmbuild -bb \
        --buildroot [filenode path $rpmBuildDir] \
        --target $arch-intel-linux \
        [filenode path $spec] >@stdout 2>@stderr

    # copy generated RPM
    set rpms [glob -path [filenode path $rpmOutputDir]/ */*.rpm]
    if {[llength $rpms] != 1} {
        error "Expected only one generated RPM, but the following found: $rpms"
    }
    filenode create [lindex $rpms 0] [file tail [lindex $rpms 0]]
}

# Convert starkit architecture to RPM architecture
proc rpmArchitecture {arch} {
    switch $arch {
        x86 {
            return i386
        }
        amd64 {
            return x86_64
        }
        default {
            error "Unknown architecture for converting to RPM-ish: $arch"
        }
    }
}

# Check that rpm package building is supported
proc isSupported {} {
    expr {[auto_execok rpmbuild] ne ""}
}

namespace export \
    rpm \
    isSupported
namespace ensemble create
}
}
